import random
import re

from django.core.mail import send_mail
from django.shortcuts import render

# Create your views here.
from django_redis import get_redis_connection
from rest_framework import mixins
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.generics import CreateAPIView, GenericAPIView
from rest_framework.mixins import CreateModelMixin
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import GenericViewSet
from rest_framework_jwt.views import ObtainJSONWebToken

from goods.models import SKU
from goods.serializers import UserHistorySerializer, HotGoodsSerializer
from meiduo_mall.utils.add_cookie_redis import merge_cookie_redis
from users import serializers
from users.models import User, Address
from users.serializers import CheckSMSCodeSerializer, UserCenterSerializer
from users.tasks import send_verify_email
from users.utils import get_user_by_account
from verifications import constants
from verifications.serializers import CheckImageCodeSerializer

class CheckUserName(APIView):
    def get(self,request,username):
        count=User.objects.filter(username=username).count()
        data={'username':username,
              'count':count}
        return Response(data)


class CheckMobile(APIView):
    def get(self,request,mobile):
        count=User.objects.filter(mobile=mobile).count()
        data={'mobile':mobile,
              'count':count}
        return Response(data)



class UserViewSet(CreateAPIView):
    queryset = User.objects.all()
    # 指定哪个序列化器
    serializer_class=serializers.CreateUserSerializer


class SMSCodeTokenView(GenericAPIView):
    serializer_class=CheckImageCodeSerializer
    queryset = User.objects.all()
    def get(self,request,account):
        serializer=self.get_serializer(data=request.query_params)
        serializer.is_valid(raise_exception=True)
        # 返回一个经过处理的手机号
        user=get_user_by_account(account)
        if user is None:
            return Response({'message': '用户不存在'}, status=status.HTTP_404_NOT_FOUND)
        # generate_send_sms_code_token
        access_token = user.generate_send_sms_code_token()
        mobile=user.mobile
        mobile=re.sub(r'(\d{3})\d{4}(\d{3})', r'\1****\2',mobile)

        return Response({'mobile':mobile,'access_token':access_token})


class SMSCodeByTokenView(APIView):
    def get(self,request):
        access_token=request.query_params.get('access_token')
        mobile=User.check_send_sms_code_token(access_token)
        redis_connect = get_redis_connection('verify_codes')
        send_flag = redis_connect.get('send_flag_%s' % mobile)
        if send_flag:
            return Response({"message": "请求次数过于频繁"}, status=status.HTTP_429_TOO_MANY_REQUESTS)
        # 生成短信验证码
        sms_code = '%06d' % random.randint(0, 999999)
        print(sms_code)
        # 保存短信验证码及发送记录
        # redis_connect = get_redis_connection('verify_codes')
        redis_connect.setex('sms_code_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        redis_connect.setex('send_flag_%s' % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)
        # 发送短信
        # ccp = CCP().send_template_sms(mobile, [sms_code, constants.SMS_CODE_REDIS_EXPIRES / 60], '1')
        return Response({"message": "OK"}, status.HTTP_200_OK)


class PasswordTokenView(GenericAPIView):
    serializer_class = CheckSMSCodeSerializer
    queryset = User.objects

    def get(self,request,account):
        serializer=self.get_serializer(data=request.query_params)
        serializer.is_valid(raise_exception=True)
        user=get_user_by_account(account)
        account_token=user.generate_set_password_token()
        print(user.id)
        return Response({'user_id':user.id,'account_token':account_token})


class PasswordView(mixins.UpdateModelMixin, GenericAPIView):
    """
    用户密码
    """
    queryset = User.objects.all()
    serializer_class = serializers.ResetPasswordSerializer

    def post(self, request, pk):
        return self.update(request, pk)
# 用户中心显示ｎａｍｅ　ｉｄ　及邮件
class UserDetailView(APIView):

    def get(self,request):
        user=request.user
        data={
            'id':user.id,
            'username':user.username,
            'mobile':user.mobile,
            'email':user.email,
            'email_active':user.email_active
        }
        '''
        Response默认不写data,但是也可以写data={xxxxx}
        '''
        return Response(data)

# 保存邮箱并且发送短信
class EmailView(APIView):

    def post(self,request):
        email=request.data.get('email')
        if not re.match(r'^[0-9a-zA-Z_]{0,19}@[0-9a-zA-Z]{1,13}\.[com,cn,net]{1,3}$',email):
            return Response({'message':'email格式不正确'})
        user = request.user
        user.email=email
        user.save()
        # 生成验证地址
        verify_url=user.generate_verify_email_url()
        # 发送短信
        send_verify_email(email,verify_url)
        return Response({'message':'ok'})


# 进行电子邮件验证
class VerifyEmailView(APIView):
    # 接受token
    def get(self,request):
        token=request.query_params.get('token')
        if not token:
            return Response({'message':'没有token'})
        # 校验token
        user=User.check_verify_email_token(token)
        # 保存email_active
        user.email_active=True
        user.save()
        return Response({'message':'ok'})



# 收货地址增删改查
class AddressViewSet(mixins.CreateModelMixin, mixins.UpdateModelMixin, GenericViewSet):
    serializer_class = serializers.UserAddressSerializer
    permissions = [IsAuthenticated]

    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False)

    def list(self,request):
        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)
        user = self.request.user
        return Response({
            'user_id': user.id,
            'default_address_id': user.default_address_id,
            'limit': constants.USER_ADDRESS_COUNTS_LIMIT,
            'addresses': serializer.data,
        })

    def create(self, request, *args, **kwargs):
        """
        保存用户地址数据
        """
        # 检查用户地址数据数目不能超过上限
        count = request.user.addresses.count()
        if count >= constants.USER_ADDRESS_COUNTS_LIMIT:
            return Response({'message': '保存地址数据已达到上限'}, status=status.HTTP_400_BAD_REQUEST)

        return super().create(request, *args, **kwargs)

    def destroy(self, request, *args, **kwargs):
        """
        处理删除
        """
        address = self.get_object()

        # 进行逻辑删除
        address.is_deleted = True
        address.save()

        return Response(status=status.HTTP_204_NO_CONTENT)

    @action(methods=['put'], detail=True)
    def status(self, request, pk=None, address_id=None):
        """
        设置默认地址
        """
        address = self.get_object()
        request.user.default_address = address
        request.user.save()
        return Response({'message': 'OK'}, status=status.HTTP_200_OK)

    @action(methods=['put'], detail=True)
    def title(self, request, pk=None, address_id=None):
        """
        修改标题
        """
        address = self.get_object()
        serializer = serializers.AddressTitleSerializer(instance=address, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)



class UserHistory(mixins.CreateModelMixin,GenericAPIView):
    pagination_class=None
    serializer_class =UserHistorySerializer
    queryset=SKU.objects.all()
    permissions = [IsAuthenticated]
    # 请求是post　人家帮你写好creat方法但是不会调用，要在post方法中调用create方法
    def post(self,request):
        # print('静茹到了函数中')
        return self.create(request)

    def get(self,request):
        user_id=request.user.id
        redis_conect = get_redis_connection('history')
        '''lrange(name, start, end)'''
        # 在、这里哪的是redis中存的id
        history=redis_conect.lrange('history_%s' % user_id,0,-1)
        goods_list=[]
        for ret in history:
            # 遍历通过id查询数据
            goods=SKU.objects.get(id=ret)
            goods_list.append(goods)
        # print(goods_list)
        serializer=UserCenterSerializer(goods_list,many=True)
        return Response(serializer.data)


class Login_Add_redis(ObtainJSONWebToken):
    def post(self, request, *args, **kwargs):
        response=super().post(request)
        serializer = self.get_serializer(data=request.data)

        if serializer.is_valid():
            user = serializer.object.get('user') or request.user
            response=merge_cookie_redis(request,response,user)

        return response